package com.example.webservice.client;

import com.alibaba.fastjson.JSON;
import com.example.webservice.entity.UserResult;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.junit.Test;

import java.util.List;

/**
 * @author 彭长云
 * @Description:
 * @date 2019/1/7 14:04
 */
public class WebServiceClientHandler {

    /**
     *
     *@author： 彭长云
     * @Description:
     * @date： 2019/1/7 17:03
     * @param： [wsdlUrl：webservice地址, method:方法, params参数数组]
     * @return： java.lang.Object
     */
    public Object client(String wsdlUrl,String method, String... params) {
        // 创建动态客户端
        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
        Client client = dcf.createClient(wsdlUrl);

        Object[] objects = new Object[0];
        try {
            // invoke("方法名",参数1,参数2,参数3....);
            objects = client.invoke(method, params);
        } catch (java.lang.Exception e) {
            e.printStackTrace();
        }
        return objects[0];
    }

    /**
     *测试调用发布的服务
     */
    @Test
    public void testMyWebservice() {
            String wsdlUrl = "http://localhost:8080/webservice/services/TestService?wsdl";
            WebServiceClientHandler handler = new WebServiceClientHandler();
            Object obj = handler.client(wsdlUrl,"login","admin","123");
            System.out.println("返回数据:" +obj);

            //调用getUserList方法
            obj = handler.client(wsdlUrl,"getUserList");
            System.out.println("返回数据:" + obj);
            //json转实体对象集合
            List<UserResult> list = JSON.parseArray(obj.toString(), UserResult.class);
            for(UserResult user : list){
                System.out.println(user.getName() + "---> " + user.getAge() );
            }
    }

    /**
     *英汉互译
     */
    @Test
    public void testTranslatorWebService(){
        String wsdlUrl = "http://www.webxml.com.cn/WebServices/TranslatorWebService.asmx?wsdl";
        WebServiceClientHandler handler = new WebServiceClientHandler();
        Object obj = handler.client(wsdlUrl,"getEnCnTwoWayTranslator","are");
        System.out.println(JSON.toJSONString(obj));
    }

    @Test
    public void testChinaTVprogramWebService(){
        String wsdlUrl = "http://www.webxml.com.cn/webservices/ChinaTVprogramWebService.asmx?wsdl";
        WebServiceClientHandler handler = new WebServiceClientHandler();
        Object obj = handler.client(wsdlUrl,"getAreaDataSet");
        System.out.println(JSON.toJSONString(obj));
    }
}
